﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using System.IO.Packaging;

namespace BingImages
{
    class Archive
    {
        private const long BUFFER_SIZE = 4096;
        private static Folder _folder = new Folder();

        public static void setArchive(string archivePicture, string archiveDelete, string path) 
        {
            if (archivePicture == "True")
            {
                if (_folder.exist(path))
                {
                    string year = "";
                    int tempYear = 0;
                    string month = "";
                    int tempMonth = 0;
                    string previousMonth = "";
                    FileInfo[] files = null;
                    FileInfo[] totalFiles = null;

                    // Récupération de l'année actuelle et du mois précédent
                    year = DateTime.Now.Year.ToString();
                    month = DateTime.Now.Month.ToString("d2");

                    if(month != "01")
                    {
                        tempMonth = int.Parse(month) - 1;
                        previousMonth = tempMonth.ToString("d2");
                    }
                    else
                    {
                        tempYear = int.Parse(year) - 1;
                        year = tempYear.ToString();
                        previousMonth = "12";
                    }

                    files = _folder.getFiles(new DirectoryInfo(path), year + "-" + previousMonth + "-*.png");
                    totalFiles = _folder.getFiles(new DirectoryInfo(path), "*.png");

                    int size = totalFiles.Length;

                    if (files.Length > 0)
                    {
                        string archivePath = path + @"\Archives";
                        bool isExists = Directory.Exists(archivePath);

                        // Création du dossier "Archives" s'il n'existe pas
                        if (!isExists)
                        {
                            Directory.CreateDirectory(archivePath);
                        }

                        foreach (FileInfo file in files)
                        {
                            // Ajout de chaque image dans l'archive
                            addFileToZip(archivePath + @"\BingImages-" + previousMonth + "-" + year + ".zip", file.FullName);

                            if (archivePicture == "True" && archiveDelete == "True")
                            {
                                if (size > 9)
                                {
                                    // Suppression des images archivées précédemment
                                    file.Delete();
                                    _folder.deleteFile(_folder.wallpaperPath, Path.GetFileNameWithoutExtension(file.Name) + ".jpg");
                                }

                                size--;
                            }
                        }
                    }
                }
            }        
        }

        private static void addFileToZip(string zipFilename, string fileToAdd)
        {
            using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
            {
                string fileName = ".\\" + Path.GetFileName(fileToAdd);

                Uri uri = PackUriHelper.CreatePartUri(new Uri(fileName, UriKind.Relative));
                if (zip.PartExists(uri))
                {
                    zip.DeletePart(uri);
                }

                PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
                
                using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (Stream dest = part.GetStream())
                    {
                        copyStream(fileStream, dest);
                    }
                }
            }
        }

        private static void copyStream(System.IO.FileStream inputStream, System.IO.Stream outputStream)
        {
            long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
            byte[] buffer = new byte[bufferSize];
            int bytesRead = 0;
            long bytesWritten = 0;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
                bytesWritten += bufferSize;
            }
        }
    }
}
